package cn.clq.ssmshiro.dao.impl;

import cn.clq.ssmshiro.dao.UserDao;
import cn.clq.ssmshiro.pojo.User;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Component
public class UserDaoImpl implements UserDao{

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    public User getUserByUsername(String username) {
        String sql = "select * from users where username = ?";
        List<User> users = jdbcTemplate.query(sql,new String[]{username},new RowMapper<User>() {
            @Override
            public User mapRow(ResultSet rs, int rowNum) throws SQLException {
                User user = new User();
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                return user;
            }
        });
        if(users==null||users.size()==0)
            return null;
        return users.get(0);
    }

    @Override
    public List<String> getRolesByUsername(String username) {
        System.out.println("从数据库中获取权限数据");
        String sql = "select * from user_roles where username=?";
        List<String> list = jdbcTemplate.query(sql, new String[]{username}, new RowMapper<String>() {
            @Override
            public String mapRow(ResultSet rs, int rowNum) throws SQLException {
                String role = rs.getString("role_name");
                return role;
            }
        });
        return list;
    }
}
